<template>
  <div class="mental-detail pad">
    <el-page-header class="page-header" @back="goBack" :content="title">
    </el-page-header>
    <el-button type="primary" @click="openAddDialog">添加题目</el-button>
    <el-table border stripe :data="questions" class="m-t-b" v-loading="loading">
      <el-table-column fixed="left" label="题目" prop="title" width="166"></el-table-column>
      <!-- <el-table-column label="创建时间" prop="createDate"></el-table-column> -->
      <!-- <el-table-column label="最近修改时间" prop="updateDate"></el-table-column> -->
      <el-table-column label="a选项" prop="a"></el-table-column>
      <el-table-column label="a选项分数" prop="as"></el-table-column>
      <el-table-column label="b选项" prop="b"></el-table-column>
      <el-table-column label="b选项分数" prop="bs"></el-table-column>
      <el-table-column label="c选项" prop="c"></el-table-column>
      <el-table-column label="c选项分数" prop="cs"></el-table-column>
      <el-table-column label="d选项" prop="d"></el-table-column>
      <el-table-column label="d选项分数" prop="ds"></el-table-column>
      <el-table-column label="e选项" prop="e"></el-table-column>
      <el-table-column label="e选项分数" prop="es"></el-table-column>
      <el-table-column label="f选项" prop="f"></el-table-column>
      <el-table-column label="f选项分数" prop="fs"></el-table-column>
      <el-table-column label="j选项" prop="j"></el-table-column>
      <el-table-column label="j选项分数" prop="js"></el-table-column>
      <el-table-column label="h选项" prop="h"></el-table-column>
      <el-table-column label="h选项分数" prop="hs"></el-table-column>
      <el-table-column label="是否启用" fixed="right" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enable"
            active-text="是"
            inactive-text="否"
            @change="changeStatus(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="100">
        <template slot-scope="scope">
          <el-button circle icon="el-icon-delete" type="danger" @click="deleteMentalQuestion(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="flex m-t-b"
      :page-size="pageSize"
      layout="prev, pager, next"
      @current-change="handlePagi"
      :total="total">
    </el-pagination>
    <el-dialog title="添加题目" :visible.sync="showDialog">
      <el-form :model="mental" :rules="rules" ref="question">
        <el-form-item label="题目" prop="questions">
          <el-select v-model="mental.questions" multiple filterable style="width:70%">
            <el-option class="activeItem" v-for="(item, i) in items" :key="i" :label="item.title" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button type="primary" @click="addQuestion('question')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getQuestionByMentalId,
  addQuestion2Mental,
  getAllMentalQuestion,
  changeMentalQuestionStatus,
  deleteQuestionFromMental
} from '../api'

export default {
  name: 'MentalDetail',
  props: ['id'],
  data () {
    return {
      title: '',
      pageSize: 10,
      showDialog: false,
      loading: true,
      questions: [],
      items: [],
      mental: {
        questions: ''
      },
      rules: {
        questions: [
          { required: true, message: '请选择题目', trigger: 'blur' }
        ]
      },
      total: 0
    }
  },
  methods: {
    goBack () {
      history.back()
    },
    openAddDialog () {
      this.mental.questions = '';
      this.showDialog = true
    },
    changeStatus (row) { // 改变状态
      this.$confirm(`确定${row.enable ? '启用' : '禁用'}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeMentalQuestionStatus({
          "mentalMiddleId": row.mentalMiddleId,
          "enable": row.enable ? '1' : '0'
        })
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.fetchAllQuestion(1)
          } else {
            this.$message.error(res.data.msg || '网络异常!')
          }
        })
        .catch(e => {
          this.$message.error('网络异常!')
        })
      }).catch(() => {
        row.enable = !row.enable;
        this.$message({
          type: 'info',
          message: '已取消操作'
        });          
      })
    },
    deleteMentalQuestion (data) {
      this.$confirm(`确定将该题目从该心理测试表中删除?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        deleteQuestionFromMental(data.mentalMiddleId)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchAllQuestion(1)
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          }
        })
        .catch(e => {
          this.$message.error('服务异常!')
        })
      })
      .catch(e => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    },
    fetchQuestions () {
      getAllMentalQuestion()
      .then(res => {
        if (res.data.code === 1) {
          this.items = res.data.data
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    fetchAllQuestion (index) {
      this.loading = true;
      getQuestionByMentalId(Number(this.id), {
        count: this.pageSize,
        index
      })
      .then(res => {
        this.loading = false;
        if (res.data.code === 1) {
          this.total = res.data.data.totalRecord || 0;
          const list = res.data.data.list || [];
          list.forEach(item => {
            item.enable = item.enable == '1' ? true : false;
            item.itemId = item.id
          });
          this.questions = list
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.loading = false;
        this.$message.error('网络异常!')
      })
    },
    hideDialog () {
      this.showDialog = false
    },
    addQuestion (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          const list = this.mental.questions.map(item => {
            return [this.id, item.toString()]
          });
          addQuestion2Mental({
            tbMentalMiddle: list
          })
          .then(res => {
            if (res.data.code === 1) {
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
              this.showDialog = false;
              this.fetchAllQuestion(1)
            } else {
              this.$message.error(res.data.msg || '网络异常!')
            }
          })
          .catch(e => {
            this.$message.error('网络异常!')
          })
        } else {
          return false
        }
      })
    },
    handlePagi (page) {
      this.fetchAllQuestion(page)
    }
  },
  created () {
    let path = this.$route.meta.path;
    this.title = path[path.length - 1];
    this.fetchAllQuestion(1);
    this.fetchQuestions()
  }
}
</script>
<style lang="scss">
  .mental-detail {

  }
  .activeItem {
    width: 400px;
  }
</style>
